<template>
  <div class="waste-type-container">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="废品类型名称">
          <el-input v-model="searchForm.name" placeholder="请输入废品类型名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="wasteList"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column prop="wasteTypeName" label="类型名称" width="500"></el-table-column>
      <el-table-column prop="price" label="价格" width="500">
        <template #default="scope">
          {{ scope.row.price }} {{ scope.row.priceUtil }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增: 分页组件 -->
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination-container"
    ></el-pagination>

    <!-- 新增/修改对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增废品类型' : '修改废品类型'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="500px"
      @close="cancelDialog"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="类型名称" prop="wasteTypeName">
          <el-input v-model="editForm.wasteTypeName" placeholder="请输入废品类型名称"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="editForm.price"
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%;"
            :disabled="editForm.priceUtil === '面议'"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="价格单位" prop="priceUtil">
          <el-select v-model="editForm.priceUtil" placeholder="请选择价格单位">
            <el-option
              v-for="item in priceUnitOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      loading: false,
      wasteList: [],
      total: 0, // 新增: 总条数
      currentPage: 1, // 新增: 当前页码
      pageSize: 10, // 新增: 每页条数
      priceUnitOptions: [ // 新增: 价格单位选项
        { value: '元/斤', label: '元/斤' },
        { value: '元/个', label: '元/个' },
        { value: '面议', label: '面议' }
      ],
      searchForm: {
        name: ''
      },
      dialogVisible: false,
      dialogType: 'add',
      editForm: {
        id: null,
        wasteTypeName: '',
        price: 0,
        priceUtil: ''
      },
      rules: {
        wasteTypeName: [
          { required: true, message: '请输入废品类型名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        priceUtil: [
          { required: true, message: '请输入价格单位', trigger: 'change' }
        ]
      }
    };
  },
  watch: {
    // 新增: 监听价格单位变化
    'editForm.priceUtil': function(newVal) {
      if (newVal === '面议') {
        this.editForm.price = '';
      }
    }
  },
  methods: {
    // 根据名称查询
    handleSearch() {
      if (!this.searchForm.name) {
        this.fetchWasteTypes();
        return;
      }
      this.loading = true;
      axios.get('/zsd-waste/waste-type/getWasteTypeByName/' + this.searchForm.name)
        .then(response => {
          if (response.data.code === 200) {
            if (response.data.data) {
              this.wasteList = [response.data.data];
            } else {
              this.wasteList = [];
              this.$message.info('未找到匹配的废品类型');
            }
          } else {
            this.$message.error(response.data.msg || '查询失败');
          }
        })
        .catch(error => {
          console.error('查询失败', error);
          this.$message.error('查询失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 重置查询
    resetSearch() {
      this.searchForm.name = '';
      this.fetchWasteTypes();
    },

    // 修改: 获取废品类型列表，添加分页处理
    fetchWasteTypes() {
      this.loading = true;
      axios.get('/zsd-waste/waste-type/selWasteType')
        .then(response => {
          if (response.data.code === 200) {
            const allData = response.data.data;
            this.total = allData.length;
            // 根据当前页码和每页条数进行分页
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            this.wasteList = allData.slice(start, end);
          } else {
            this.$message.error(response.data.msg || '获取数据失败');
          }
        })
        .catch(error => {
          console.error('获取废品类型列表失败', error);
          this.$message.error('获取数据失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 新增: 处理分页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 重置当前页码为第一页
      this.fetchWasteTypes();
    },

    // 新增: 处理当前页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchWasteTypes();
    },

    // 打开新增对话框
    handleAdd() {
      this.dialogType = 'add';
      this.editForm = {
        id: null,
        wasteTypeName: '',
        price: 0,
        priceUtil: ''
      };
      this.dialogVisible = true;
      console.log('打开新增对话框', { dialogVisible: this.dialogVisible, dialogType: this.dialogType });
    },

    // 打开编辑对话框
    handleEdit(row) {
      this.dialogType = 'edit';
      this.editForm = { ...row };
      this.dialogVisible = true;
      console.log('打开编辑对话框', { dialogVisible: this.dialogVisible, dialogType: this.dialogType, editForm: this.editForm });
    },

    // 取消对话框
    cancelDialog() {
      this.dialogVisible = false;
      if (this.$refs.editFormRef) {
        this.$refs.editFormRef.resetFields();
      }
      this.editForm = {
        id: null,
        wasteTypeName: '',
        price: 0,
        priceUtil: ''
      };
    },

    // 删除废品类型
    handleDelete(row) {
      this.$confirm('确认删除该废品类型吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/zsd-waste/waste-type/deleteWasteType/' + row.id)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('删除成功');
              this.fetchWasteTypes();
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除失败', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 修改: 提交新增，添加分页参数
    submitAdd() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          const params = {
            wasteTypeName: this.editForm.wasteTypeName,
            price: this.editForm.priceUtil === '面议' ? null : this.editForm.price,
            priceUtil: this.editForm.priceUtil,
            pageNum: this.currentPage,
            pageSize: this.pageSize
          };

          console.log('新增提交的数据:', params);

          axios.put('/zsd-waste/waste-type/insertWasteType', null, { params })
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.fetchWasteTypes();
              } else {
                this.$message.error(response.data.msg || '添加失败');
              }
            })
            .catch(error => {
              console.error('添加失败', error);
              const errorMsg = error.response && error.response.data && error.response.data.msg
                ? error.response.data.msg
                : error.message;
              this.$message.error('添加失败: ' + errorMsg);
            });
        }
      });
    },

    // 修改: 提交修改，添加分页参数
    submitEdit() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) {
          return;
        }

        const wasteType = {
          id: this.editForm.id,
          wasteTypeName: this.editForm.wasteTypeName,
          price: this.editForm.priceUtil === '面议' ? null : this.editForm.price,
          priceUtil: this.editForm.priceUtil,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        };

        this.loading = true;
        console.log('开始提交修改数据:', wasteType);

        axios({
          method: 'post',
          url: '/zsd-waste/waste-type/updateWasteType',
          data: wasteType,
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(response => {
          console.log('修改请求响应:', response.data);
          if (response.data.code === 200) {
            this.dialogVisible = false;
            this.$message.success('修改成功');
            this.fetchWasteTypes();
          } else {
            this.$message.error(response.data.msg || '修改失败');
          }
        })
        .catch(error => {
          console.error('修改请求错误:', error);
          let errorMsg = '修改失败';
          if (error.response && error.response.data) {
            errorMsg = error.response.data.msg || errorMsg;
          }
          this.$message.error(errorMsg);
        })
        .finally(() => {
          this.loading = false;
        });
      });
    },

    // 确认对话框
    handleDialogConfirm() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            this.submitAdd();
          } else {
            this.submitEdit();
          }
        }
      });
    }
  },
  created() {
    this.fetchWasteTypes();
  }
};
</script>

<style scoped>
.waste-type-container {
  padding: 20px;
}

.search-bar {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 新增: 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.el-dialog__body {
  padding: 20px 40px;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 添加响应式样式 */
@media screen and (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
  }
}
</style>
